package com.stone.controller;

import com.stone.redis.lock.DistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class TestController {

    @GetMapping("test")
    public String getTest() {
        return "test";
    }

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private DefaultRedisScript<Long> script;

    @PostConstruct
    public void init() {
        script = new DefaultRedisScript<>();
        script.setResultType(Long.class);
        script.setScriptSource(new ResourceScriptSource(new ClassPathResource("lock.lua")));
    }

    @PostMapping(value = "/addUser")
    public String createOrder(String user) {

        String key = user;
        // 如下为使用UUID、固定字符串，固定字符串容易出现线程不安全
        String value = UUID.randomUUID().toString().replace("-", "");
        // String value = "123";
        /*
         * setIfAbsent <=> SET key value [NX] [XX] [EX <seconds>] [PX [millseconds]]
         * set expire time 5 mins
         */
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, value, 5000, TimeUnit.MILLISECONDS);
        if (flag) {
            log.info("{} 锁定成功，开始处理业务", key);
            try {
                /** 模拟处理业务逻辑 **/
                Thread.sleep(1000 * 30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            /** 判断是否是key对应的value **/
            Object lockValue = redisTemplate.opsForValue().get(key);
            if (lockValue != null && lockValue.equals(value)) {
                redisTemplate.delete(key);
                log.info("{} 解锁成功，结束处理业务", key);
            }
            return "SUCCESS";
        } else {
            log.info("{} 获取锁失败", key);
            return "请稍后再试...";
        }
    }


    @PostMapping(value = "/addUser2")
    public String addUser2(String user) {

        String key = user;
        String value = UUID.randomUUID().toString().replace("-", "");
        /*
         * setIfAbsent <=> SET key value [NX] [XX] [EX <seconds>] [PX [millseconds]]
         * set expire time 5 mins
         */
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, value, 20000, TimeUnit.MILLISECONDS);
        if (flag) {
            log.info("{} 锁定成功，开始处理业务", key);
            try {
                /** 模拟处理业务逻辑 **/
                Thread.sleep(1000 * 10);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            /** 业务逻辑处理完毕，释放锁 **/
            String lockValue = (String) redisTemplate.opsForValue().get(key);
            if (lockValue != null && lockValue.equals(value)) {
                System.out.println("lockValue========：" + lockValue);
                List<String> keys = new ArrayList<>();
                keys.add(key);
                Long execute = redisTemplate.execute(script, keys, lockValue);
                System.out.println("execute执行结果，1表示执行del，0表示未执行 ===== " + execute);
                log.info("{} 解锁成功，结束处理业务", key);
            }
            return "SUCCESS";
        } else {
            log.info("{} 获取锁失败", key);
            return "请稍后再试...";
        }
    }


    @Autowired
    private DistributedLock lock;

    @Resource
    RedissonClient redissonClient;

    @PostMapping(value = "/addUser3")
    public String addUser3(String user) {
        String key = user;
        HashMap<String, String> map = new HashMap<>(10);
        map.put("str", "str");
        RLock lock = redissonClient.getLock(key);
        try {
            boolean b = lock.tryLock();
            log.info("the flag : " + b);
            if (b) {
                /** 模拟处理业务逻辑 **/
                log.info("开始处理业务");
                Thread.sleep(1000 * 30);
                lock.unlock();
            }else {
                log.info("获取锁失败");
                return "false";
            }
        } catch (InterruptedException e) {
            log.info("拿锁失败");
            e.printStackTrace();
        }
        return "SUSSESS";
    }
}
